'use strict'
let Mail = require('./model').Mail
let Ids = require('./model').Ids
let serverConfig = require('../../config/serverConfig').serverConfig
let serverId = serverConfig.serverId

/**
 * 新建角色并保存
 */
exports.newAndSave = function(playerId, title, content, items, money, gold, callback) {
    Ids.findAndModify({
        _id: serverId
    }, [], {
        $inc: {
            mailId: 1
        }
    }, {}, function(err, res) {
        if (err || !res.value) throw err;
        let id = res.value.mailId * 1000 + serverId //id后面3位是服务器id
        let mail = new Mail({
            _id: id,
            playerId: playerId,
            title: title || '',
            content: content || '',
            items: items || [],
            gold: gold || 0,
            time: new Date().getTime(), //发送的时间
            read: 0, //0未读1已读
        })
        mail.save(callback)
    })
}


exports.getMailsByQuerys = function(query, page, limit, callback) {
    Mail.find(query)
        .skip(page * limit)
        .limit(limit + 1)
        .sort('-time')
        .exec(callback)
}

exports.getMailByQuery = function(query, callback){
  Mail.findOne(query, callback)
}

/**
 * 根据查询条件, 更新
 */
exports.updateMailById = function(mailId, field, callback) {
    Mail.update({
        _id: mailId
    }, field, {}, callback)
}

/**
 * 根据查询条件, 删除物品
 */
exports.removeMailByQuery = function(query, callback) {
    Mail.remove(query, callback)
}
